<template>
    <view class="login-container">
        <!-- 返回按钮 -->
        <view class="back-btn" @click="handleBack" :style="backBtnStyle">
            <image src="../../static/left.png" mode="widthFix" class="back-icon"></image>
            <view>返回</view>
        </view>
        
        <image src="https://puqinzc.oss-cn-beijing.aliyuncs.com/d0c6fee22789b9b8b14ab0e5b9fbf761.png" mode="widthFix" class="logo"></image>
        <view class="head">
            <view class="hello">您好，</view>
            <view class="welcome">欢迎来到枣庄市红十字会</view>
        </view>
        
        <view class="form" v-if="loginMode === 'phone'">
            <view class="form-item">
                <view class="form-item-input">
                    <input type="number" v-model="formData.phone" maxlength="11" placeholder="请输入手机号" />
                </view>
            </view>
            <view class="form-item">
                <view class="form-item-input">  
                    <input type="number" v-model="formData.code" maxlength="6" placeholder="请输入验证码" />
                </view>
                <view class="form-item-btn primary-color" @click="handleGetCode" :class="{ disabled: counting }">
                    {{ counting ? `${countdown}s` : '点击获取' }}
                </view>
            </view>

            <!-- 登录/注册即同意《隐私权政策》《用户协议》 -->
            <!-- <view class="agreement">
                <view class="agreement-text">
                    登录/注册即同意
                </view>
                <view class="agreement-link primary-color">
                    <text @click="handlePrivacy">《隐私权政策》</text>
                    <text @click="handleAgreement">《用户协议》</text>
                </view>
            </view> -->

        </view>

        <view class="btn">
            <template v-if="loginMode === 'phone'">
                <view class="primary-btn" @click="handleLogin">一键登录/注册</view>
            </template>
            <template v-else>
                <!-- #ifdef MP-WEIXIN -->
                <button class="primary-btn wechat-btn" open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">手机号快捷登录</button>
                <!-- #endif -->
                <!-- #ifndef MP-WEIXIN -->
                <view class="primary-btn" @click="handleWechatLogin">手机号快捷登录</view>
                <!-- #endif -->
            </template>
        </view>
        
        <!-- 分隔线 -->
        <view class="divider">
            <view class="divider-line"></view>
            <view class="divider-text">其他登录方式</view>
            <view class="divider-line"></view>
        </view>
        
        <!-- 手机号快捷登录 -->
        <view class="wechat-login" v-if="loginMode === 'phone'" @click="switchToWechat">
            <view class="wechat-icon">
               <image src="../../static/wechat.png" mode="aspectFit" class="wechat-img"></image>
            </view>
            <view class="wechat-text">手机号快捷登录</view>
        </view>
        
        <!-- 手机验证码登录 -->
        <view class="phone-login" v-if="loginMode === 'wechat'" @click="switchToPhone">
            <view class="phone-icon">
                <image src="../../static/code.png" mode="aspectFit" class="phone-img"></image>
            </view>
            <view class="phone-text">手机验证码登录</view>
        </view>

    </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { userLogin, sendSmsCode, quickReg, wxLogin, wxGetUserPhone } from '@/utils/api.js'
import { saveLoginInfo, isLoggedIn } from '@/utils/user.js'
import { handleLoginSuccess } from '@/utils/loginGuard.js'

const formData = reactive({
    phone: '',
    code: ''
})

const counting = ref(false)
const countdown = ref(60)
const continueReg = ref(false) // 是否继续注册状态
const loginMode = ref('wechat') // 登录方式：'phone' | 'wechat'
const wechatSession = ref({ code: '', openid: '' }) // 存储微信登录code与openid

// 检查登录状态并跳转
const checkLoginAndRedirect = () => {
    if (isLoggedIn()) {
        uni.reLaunch({
            url: '/pages/index/index'
        })
    }
}

// 页面加载时检查登录状态
onMounted(() => {
    checkLoginAndRedirect()
})

// 页面显示时检查登录状态
onShow(() => {
    checkLoginAndRedirect()
})

// 验证手机号
const validatePhone = (phone) => {
    const reg = /^1[3-9]\d{9}$/
    return reg.test(phone)
}

// 获取验证码
const handleGetCode = async () => {
    if (counting.value) return
    
    if (!formData.phone) {
        uni.showToast({
            title: '请输入手机号',
            icon: 'none'
        })
        return
    }
    
    if (!validatePhone(formData.phone)) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
        })
        return
    }
    
    try {
        const res = await sendSmsCode(formData.phone, continueReg.value)
        
        if (res.code === 0) {
            counting.value = true
            countdown.value = 60
			
            
            const timer = setInterval(() => {
                countdown.value--
                if (countdown.value <= 0) {
                    clearInterval(timer)
                    counting.value = false
                }
            }, 1000)
            
            uni.showToast({
                title: '验证码已发送',
                icon: 'success'
            })
        } else if (res.code === 402) {
            // 用户未注册，询问是否继续注册
            uni.showModal({
                title: '提示',
                content: '该手机号未注册，是否继续注册？',
                success: (modalRes) => {
                    if (modalRes.confirm) {
                        // 用户确认注册，设置状态并重新发送验证码
                        continueReg.value = true
                        handleGetCode()
                    }
                }
            })
        } else {
            uni.showToast({
                title: res.message || '获取验证码失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('获取验证码失败:', error)
        uni.showToast({
            title: '获取验证码失败',
            icon: 'none'
        })
    }
}

// 登录/注册
const handleLogin = async () => {
    if (loginMode.value === 'wechat') {
        // 微信登录模式
        await handleWechatLogin()
        return
    }
    
    // 手机验证码登录模式
    if (!formData.phone) {
        uni.showToast({
            title: '请输入手机号',
            icon: 'none'
        })
        return
    }
    
    if (!validatePhone(formData.phone)) {
        uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
        })
        return
    }
    
    if (!formData.code) {
        uni.showToast({
            title: '请输入验证码',
            icon: 'none'
        })
        return
    }
    
    try {
        let res
        
        if (continueReg.value) {
            // 快速注册
            res = await quickReg({
                phone: formData.phone,
                smsCode: formData.code
            })
        } else {
            // 正常登录
            res = await userLogin({
                phone: formData.phone,
                smsCode: formData.code
            })
        }
        
        if (res.code === 0) {
            // 保存登录信息
            const loginData = {
                token: res.data?.token || res.data?.accessToken || res.token,
                userInfo: res.data
            }
            
            saveLoginInfo(loginData)
            
            uni.showToast({
                title: continueReg.value ? '注册成功' : '登录成功',
                icon: 'success'
            })
            
            // 登录成功后处理跳转
            setTimeout(() => {
                handleLoginSuccess()
            }, 1500)
        } else {
            uni.showToast({
                title: res.message || (continueReg.value ? '注册失败' : '登录失败'),
                icon: 'none'
            })
        }
    } catch (error) {
        console.error(continueReg.value ? '注册失败:' : '登录失败:', error)
        uni.showToast({
            title: continueReg.value ? '注册失败' : '登录失败',
            icon: 'none'
        })
    }
}

// 查看隐私政策
const handlePrivacy = () => {
    // TODO: 跳转到隐私政策页面
    uni.navigateTo({
        url: '/pages/privacy/index'
    })
}

// 查看用户协议
const handleAgreement = () => {
    // TODO: 跳转到用户协议页面
    uni.navigateTo({
        url: '/pages/agreement/index'
    })
}

// 返回上一页
const handleBack = () => {
    uni.navigateBack()
}

// 获取胶囊位置
const getCapsuleInfo = () => {
    try {
        const systemInfo = uni.getSystemInfoSync()
        const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
        const statusBarHeight = systemInfo.statusBarHeight || 0
        const menuButtonHeight = menuButtonInfo.height || 32
        const menuButtonTop = menuButtonInfo.top || (statusBarHeight + 4)
        
        return {
            statusBarHeight,
            menuButtonHeight,
            menuButtonTop
        }
    } catch (error) {
        console.error('获取胶囊信息失败:', error)
        return {
            statusBarHeight: 20,
            menuButtonHeight: 32,
            menuButtonTop: 24
        }
    }
}

// 返回按钮样式
const backBtnStyle = ref({})

onMounted(() => {
    const { statusBarHeight, menuButtonHeight, menuButtonTop } = getCapsuleInfo()
    
    // 计算返回按钮位置，使其与胶囊垂直居中对齐
    const backBtnTop = menuButtonTop
    const backBtnLeft = 24
    
    backBtnStyle.value = {
        top: `${backBtnTop}px`,
        left: `${backBtnLeft}px`,
        height: `${menuButtonHeight}px`
    }
    
    console.log('胶囊信息:', { statusBarHeight, menuButtonHeight, menuButtonTop })
    console.log('返回按钮样式:', backBtnStyle.value)
})


// 手机号快捷登录（仅校验并建立会话，不获取手机号）
const handleWechatLogin = async () => {
    try {
        uni.showLoading({
            title: '登录中...'
        })
        
        // 获取微信登录凭证
        const loginRes = await uni.login({
            provider: 'weixin'
        })
        
        if (loginRes.code) {
            console.log('微信登录code:', loginRes.code)
            wechatSession.value.code = loginRes.code
            
            // 仅传 code 建立会话
            const res = await wxLogin({ code: loginRes.code })
            
            if (res.code === 0) {
                // 保存登录信息
                const loginData = {
                    token: res.data?.token || res.data?.accessToken || res.token,
                    userInfo: res.data
                }
                
                saveLoginInfo(loginData)
                
                uni.hideLoading()
                uni.showToast({
                    title: '登录成功',
                    icon: 'success'
                })
                
                // 缓存 openid（供手机号接口使用）
                try {
                    wechatSession.value.openid = res.data?.openid || res.openid || ''
                } catch (e) {}
                // 仅建立会话，不立即跳转；等待手机号授权
                // 这里不跳转，改由手机号授权后统一跳转
            } else {
                uni.hideLoading()
                uni.showToast({
                    title: res.message || '微信登录失败',
                    icon: 'none'
                })
            }
        } else {
            uni.hideLoading()
            uni.showToast({
                title: '微信登录失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('微信登录失败:', error)
        uni.hideLoading()
        uni.showToast({
            title: '微信登录失败',
            icon: 'none'
        })
    }
}

// 获取手机号（微信开放能力）
const handleGetPhoneNumber = async (e) => {
    try {
        const { errMsg, code } = e.detail || {}
        if (!code) {
            uni.showToast({
                title: '获取手机号失败',
                icon: 'none'
            })
            return
        }

        // 确保有最新的微信登录code
        if (!wechatSession.value.code) {
            const loginRes = await uni.login({ provider: 'weixin' })
            if (loginRes.code) {
                wechatSession.value.code = loginRes.code
            } else {
                uni.showToast({ title: '微信登录失败', icon: 'none' })
                return
            }
        }

        uni.showLoading({ title: '登录中...' })

        // 1) 先调用 wxLogin 建立会话并拿 user/phone/openid
        const loginRes2 = await wxLogin({ code: wechatSession.value.code })
        if (loginRes2.code !== 0) {
            uni.hideLoading()
            uni.showToast({ title: loginRes2.message || '微信登录失败', icon: 'none' })
            return
        }
        const userFromWxLogin = loginRes2.data || {}
        const loginData2 = {
            token: userFromWxLogin?.token || loginRes2.data?.accessToken || loginRes2.token,
            userInfo: userFromWxLogin
        }
        // 缓存 openid（来自 wxLogin 返回）
        try {
            wechatSession.value.openid = userFromWxLogin?.openid || loginRes2.openid || ''
        } catch (e) {}
        saveLoginInfo(loginData2)

        // 2) 如果已带 phone，直接成功
        if (userFromWxLogin && userFromWxLogin.phone) {
            uni.hideLoading()
            uni.showToast({ title: '登录成功', icon: 'success' })
            setTimeout(() => {
                handleLoginSuccess()
            }, 1200)
            return
        }

        // 3) 否则，使用授权返回的手机号 code 调后端绑定手机号
        const res = await wxGetUserPhone(code, wechatSession.value.openid)
        if (res.code === 0) {
            uni.hideLoading()
            uni.showToast({ title: '登录成功', icon: 'success' })
            setTimeout(() => {
                handleLoginSuccess()
            }, 1200)
        } else {
            uni.hideLoading()
            uni.showToast({ title: res.message || '登录失败', icon: 'none' })
        }
    } catch (err) {
        console.error('获取手机号失败:', err)
        uni.hideLoading()
        uni.showToast({ title: '获取手机号失败', icon: 'none' })
    }
}

// 切换到微信登录模式
const switchToWechat = () => {
    loginMode.value = 'wechat'
    // 清空手机号和验证码
    formData.phone = ''
    formData.code = ''
    counting.value = false
    countdown.value = 60
}

// 切换到手机验证码登录模式
const switchToPhone = () => {
    loginMode.value = 'phone'
    // 清空微信登录凭证
    // 如果需要，可以在这里添加清空微信登录凭证的逻辑
}


</script>

<style lang="scss" scoped>
    .login-container{
        padding: 0 24rpx;
        background: url('https://puqinzc.oss-cn-beijing.aliyuncs.com/57d9daf3195b8a731bad1e14b337b79a.png') top center no-repeat;
        background-size: 100% auto;

        .back-btn{
            position: absolute;
            display: flex;
            align-items: center;
            justify-content: flex-start;
            z-index: 10;
            padding: 0 16rpx;

            .back-icon{
                width: 38rpx !important;
                height: 38rpx !important;
                flex-shrink: 0;
            }
            
            view{
                font-size: 28rpx;
                color: #333;
                margin-left: 8rpx;
                line-height: 1;
                display: flex;
                align-items: center;
            }
        }

        .logo{
            position: absolute;
            top: 117rpx;
            right: 54rpx;
            width: 278rpx;
            height: 252rpx;
            z-index: -1;
        }

        .head{
            padding: 268rpx 68rpx 88rpx 68rpx;

            .hello{
                font-size: 56rpx;
                font-weight: bold;
                color: rgba(0, 0, 0, 0.90);
                line-height: 72rpx;
            }

            .welcome{
                font-size: 40rpx;
                color: rgba(0, 0, 0, 0.60);
                line-height: 72rpx;
            }
        }

        .form{
            padding: 20rpx 68rpx;
            .form-item{
                height: 68rpx;
                display: flex;
                align-items: center;
                justify-content: space-between;
                border-bottom: 2rpx solid #F6F6F6;
                margin-bottom: 40rpx;

                input{
                    height: 68rpx;
                    border: none;

                    &::placeholder {
                        color: rgba(0, 0, 0, 0.26);
                    }
                }

                .form-item-btn{
                    width: 140rpx;
                    height: 68rpx;
                    line-height: 68rpx;
                    text-align: right;
                    
                    &.disabled {
                        color: #999;
                    }
                }
            }

            .agreement{
                display: flex;
                align-items: center;
                color: rgba(0, 0, 0, 0.40);
                font-size: 24rpx;

                .agreement-link{
                    cursor: pointer;
                }
            }
        }

        .btn{
            padding: 68rpx 24rpx;
            
            .primary-btn {
                background: #F15941;
                color: #fff;
                height: 88rpx;
                line-height: 88rpx;
                text-align: center;
                border-radius: 44rpx;
            }

            /* 让 button 看起来和 view 样式一致 */
            .wechat-btn {
                width: 100%;
                border: none;
                outline: none;
                padding: 0;
                margin: 0;
                display: block;
            }
        }

        .divider{
            display: flex;
            align-items: center;
            margin: 40rpx 0;
            padding: 0 90rpx;

            .divider-line{
                flex: 1;
                height: 1rpx;
                background-color: #E0E0E0;
            }

            .divider-text{
                margin: 0 40rpx;
                color: rgba(0, 0, 0, 0.40);
                font-size: 28rpx;
            }
        }

        .wechat-login,
        .phone-login{
            margin-top: 84rpx;
            padding: 0 24rpx;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            .wechat-icon,
            .phone-icon{
                width: 80rpx;
                height: 80rpx;
                border-radius: 40rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 20rpx;
                margin-bottom: 12rpx;
            }

            .wechat-img,
            .phone-img{
                width: 80rpx;
                height: 80rpx;
                display: block;
            }

            .wechat-text,
            .phone-text{
                font-size: 28rpx;
                color: rgba(0, 0, 0, 0.60);
                font-weight: bold;
            }
        }

        .phone-login{
            margin-top: 84rpx;
        }
    }
</style>